<?php

namespace app\admin\controller;

use app\admin\service\Curlear;
use app\admin\service\LoginService;
use app\common\controller\Base;
use app\admin\validate\LoginRequest;
use think\App;
use think\Exception;
use think\Request;

class Login extends Base
{
    protected $user_server;

    public function __construct(App $app = null, LoginService $adminUser)
    {
        parent::__construct($app);
        $this->user_server = $adminUser;
    }

    public function index()
    {
        $this->assign('bg_url', Curlear::huoQu(1));
        return $this->fetch('login');
    }

    /**
     * 后台登陆 提交
     * @param LoginRequest $loginRequest
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function loginFrom(LoginRequest $loginRequest, Request $request)
    {
        $data = [
            'name' => $request->param('name'),
            'password' => $request->param('password'),
        ];
        $result = $loginRequest->check($data);
        if ($result) {
            $user_info = $this->user_server->loginName(['username' => $data['name']]);
            if (!$user_info) {
                $this->error('用户不存在！');
            }

            try {
                $this->user_server->loginUser($user_info, $data);
            } catch (Exception $e) {

                $this->error($e->getMessage());
            }

            $this->success('登陆成功了！', url('/admin'));
        } else {
            $this->error($loginRequest->getError());
        }

    }


}